<?php
namespace app\api\model;
use app\admin\model\ShopLevel;
use app\admin\model\WarehouseGeneral;
use app\admin\model\WarehouseGeneralSku;
use app\api\controller\product\ProductOut;
use app\common\model\ProductOrderSpell;
use think\Db;
use traits\model\SoftDelete;
use think\facade\Log as SystemLog;

class ProductOrder extends Base
{
    use SoftDelete;
    // 设置当前模型的数据库连接
    public function orderDetail(){
        return $this->hasMany("ProductOrderDetail","order_id","id");
    }
    public function shopType(){
        return $this->hasOne("Shop","id","uid")->bind(['type'=>'type','shop_address'=>'pick_address']);
    }
    public function user(){
        return $this->hasOne("User","id","user_id")->bind("phone");
    }
    public function productSort($cartList){
        foreach ($cartList as &$value){
            $product= [];
            foreach ($value['order_detail'] as &$val){
                if(!isset($product[$val['product_id']])){
                    $product[$val['product_id']]= [
                        'cover_img' =>$val['product_cover_img'],
                        'product_name'=>$val['product_name'],
                        'skuList'     =>[]
                    ];
                }
                $product[$val['product_id']]['skuList'][]=$val;
            }
            $product = array_values($product);
            $value['order_detail'] = $product;
        }
        return $cartList;
    }
    //商品添加销量
    public function addSales($order_id){
        $where=[
            ['order_id','eq',$order_id]
        ];
        //针对购买的商品 增加销量
        $detail = (new ProductOrderDetail())->selectList($where,"id,product_id,number","id desc");
        foreach ($detail as $value){
            $res = (new Product())->where('id',$value['product_id'])->setInc("sales_actual_number",$value['number']);
            if(!$res){
                return ['code'=>0,'msg'=>'修改销量失败'];
            }
        }
        return ['code'=>1,'msg'=>'修改销量成功'];
    }

    //给商品评价
    public function orderReview($order_id,$source,$type,$content,$user_id){
        $where=[
            ['order_id','eq',$order_id]
        ];
        //针对购买的商品 增加销量
        $detail = (new ProductOrderDetail())->selectList($where,"id,uid,product_id,number","id desc");
        $detail = $detail->toArray();
        $reviewList = [];
        foreach ($detail as $value){
            $reviewList[$value['product_id']] =[
                'uid'=>$value['uid'],
                'order_id'=>$order_id,
                'type'=>$type,
                'source'  =>$source,
                'content' =>$content,
                'user_id' =>$user_id,
                'product_id'=>$value['product_id'],
                'create_time'=>time()
            ];
        }
        $reviewList = array_values($reviewList);
        $res = (new ProductReview())->saveAll($reviewList);
        if(!$res){
            return ['code'=>0,'msg'=>'评价失败'];
        }
        return ['code'=>1,'msg'=>'评价成功'];
    }
    //订单回调
    public function OrderNotify($post,$pay_style,$source){
        if (isset($post['out_trade_no'])) {
            //判断是总订单还是子订单号
            if (strpos($post['out_trade_no'], "POR") !== false) {
                //总订单支付
                SystemLog::record("[支付回调]当前总订单[".$post['out_trade_no']."]进入订单回调", 'alert');

                $where =[['order_number','eq',$post['out_trade_no']]];
                $list = (new ProductOrderRelation())->findOne($where);
                $list = $list->toArray();
                if($list['pay_status']==1){
                    Db::startTrans();
                    $new["id"] = $list['id'];
                    $new["pay_style"] = $pay_style;
                    $new["pay_status"] = 2;
                    $new["pipeline_number"] = $post['trade_no'];
                    $new["source"] = $source;
                    $res = (new ProductOrderRelation())->dataUpdate($new);
                    if(!$res){
                        Db::rollback();
                        SystemLog::record("[支付回调]当前总订单[".$post['out_trade_no']."]ProductOrderRelation表更新失败", 'alert');
                        SystemLog::record($new, 'alert');
                    }
                    SystemLog::record("[支付回调]当前总订单[".$post['out_trade_no']."]ProductOrderRelation表更新成功", 'alert');
                    $update = [
                        'pay_style'=>$pay_style,
                        'source'=>$source,
                        'status'=>1,
                        'pay_time'=>time(),
                        'pay_form' =>1,
                        'pipeline_number'=>$post['trade_no']
                    ];
                    $re = $this->where("relation_id",'eq',$list['id'])->update($update);
                    if(!$re){
                        Db::rollback();
                        SystemLog::record("[支付回调]当前订单[".$post['out_trade_no']."]ProductOrder表更新失败", 'alert');
                        SystemLog::record($update, 'alert');
                    }
                    SystemLog::record("[支付回调]当前总订单[".$post['out_trade_no']."]ProductOrder表更新成功", 'alert');

                    $orderModel = $this->where("relation_id",'eq',$list['id'])->find();

                    //处理拼团单[拼团单内增加销量]
                    if($orderModel["order_type"] == 3){
                        SystemLog::record("[支付回调]当前总订单[".$post['out_trade_no']."]准备进入拼团处理接口", 'alert');
                        $res = (new ProductOrderSpell())->trueOrderSpell($orderModel['id'],$orderModel["user_id"]);
                        if(!$res){ Db::rollback(); }
                    }

                    //处理清仓订单[清仓付款后直接减库存]
                    if($orderModel["order_type"] == 2){
                        SystemLog::record("[支付回调]当前总订单[".$post['out_trade_no']."]准备进入清仓处理接口", 'alert');
                        $res = (new \app\common\model\ProductOut())->trueOutOrder($orderModel['order_type_id'],$orderModel['total_number']);
                        if(!$res){ Db::rollback(); }
                    }
                    Db::commit();
                }

            }else{
                SystemLog::write("当前子订单[".$post['out_trade_no']."]进入订单回调", 'alert');
                $where =[
                    ['order_number','eq',$post['out_trade_no']]
                ];
                $list = $this->findOne($where);
                if($list['status'] == 0){
                    $update = [
                        'pay_style'=>$pay_style,
                        'source'=>$source,
                        'status'=>1,
                        'pay_time'=>time(),
                        'pipeline_number'=>$post['trade_no'],
                        'pay_form' =>2
                    ];
                    $re = $this->where("order_number",$post['out_trade_no'])->update($update);
                    if(!$re){
                        Db::rollback();
                    }

                    //处理拼团单[拼团单内增加销量]
                    if($list["order_type"] == 3){
                        SystemLog::record("[支付回调]当前总订单[".$post['out_trade_no']."]准备进入拼团处理接口", 'alert');
                        $res = (new ProductOrderSpell())->trueOrderSpell($list['id'],$list["user_id"]);
                        if(!$res){ Db::rollback(); }
                    }

                    //处理清仓订单[清仓付款后直接减库存]
                    if($list["order_type"] == 2){
                        SystemLog::record("[支付回调]当前总订单[".$post['out_trade_no']."]准备进入清仓处理接口", 'alert');
                        $res = (new \app\common\model\ProductOut())->trueOutOrder($list['order_type_id'],$list['total_number']);
                        if(!$res){ Db::rollback(); }
                    }
                    Db::commit();
                }
            }
        }
    }



    public function shopLevel($uid,$money){
        $shop = (new Shop)->findOne([['id','eq',$uid]]);
        if(!$shop){
            return ['code'=>0,'msg'=>'商家不存在'];
        }
        $where = [
          ['uid','eq',0]
        ];
        $new = [
            'id'   =>$uid,
            'money'=>$shop['money']+$money,
            'amount'=>$shop['amount']+$money,
            'shop_level' =>$shop['shop_level'],
        ];
        $shopLevel = (new ShopLevel())->where($where)->cache(true,600)->order('level')->field("level,min_price,max_price")->select();
        foreach ($shopLevel as $value){
            if($value['max_price']>=$new['amount']&&$value['min_price']<=$new['amount']){
                $new['shop_level'] = $value['level'];
            }
        }
        $res = (new Shop())->dataUpdate($new);
        if(!$res){
            return ['code'=>0,'msg'=>'商家更新等级失败'];
        }
        return ['code'=>1,'msg'=>'商家更新等级成功'];

    }
}